package com.zlsy.es.dianping.service.impl;

import com.zlsy.es.dianping.baseexception.BizException;
import com.zlsy.es.dianping.constan.ErrorStatusEnum;
import com.zlsy.es.dianping.mapper.UserMapper;
import com.zlsy.es.dianping.pojo.model.User;
import com.zlsy.es.dianping.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Objects;

/**
 * @author zhouliang
 * @date 2020/02/29
 **/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;


    @Override
    public User getId(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public User register(User user) {
        try {
            user.setPassword(encodeByMd5(user.getPassword()));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            throw new BizException(ErrorStatusEnum.BUSINESS_ERROR);
        }
        user.setCreatedAt(new Date());
        user.setUpdatedAt(new Date());

        try {
            userMapper.insert(user);
        } catch (DuplicateKeyException e) {
            throw new BizException(ErrorStatusEnum.REGISTER_DUP_FAIL);
        }


        return getId(user.getId());
    }

    @Override
    public User login(String password, String telphone) {
        User user = null;
        try {
            user = userMapper.selectByTelphoneAndPassword(telphone, encodeByMd5(password));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            throw new BizException(ErrorStatusEnum.BUSINESS_ERROR);
        }
        if (Objects.isNull(user)) {
            throw new BizException(ErrorStatusEnum.LOGIN_FAIL);
        }
        return user;
    }

    @Override
    public Integer countAllUser() {
        return userMapper.countAllUser();
    }

    private String encodeByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确认计算方法MD5
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(messageDigest.digest(str.getBytes("utf-8")));

    }
}
